import React, { PureComponent } from "react";
import {
  Text,
  View,
  Image,
  TextInput,
  Alert,
  ScrollView,
  FlatList,
  Platform,
  TouchableOpacity,
  Keyboard,
  StyleSheet,
  Clipboard,
  DeviceEventEmitter,
  Linking,
} from "react-native";
import { SureGoods, safeAreaBottomHeight } from "../../util/AdapterUtil";
import actions from "../../models/actions";
import { connect } from "react-redux";
import NavigationBar from "../../components/navigationBar";
import image from "../../assets/image";
import Confirm from "../../components/confirm";
import ImageView from "../../components/ImageView";
import * as requestApi from "../../util/requestApi";
import FlatListEmpty from "../../components/FlatListEmpty";
import NavigationService from "../../components/NavigationService";
import _ from "lodash";

/*{
	"orderId": "pay201905240956173UF9N5K9TO2ST",
	"amount": 1,
	"payTime": "2019-05-24T07:05:48.000+0000",
	"payMode": 1,
	"payState": 1,
	"payRemarks": null,
	"refundAmount": 1,
	"companyName": "测试2222",
	"companyPhone": "18782228298",
	"name": null,
	"deliveryPhone": null,
	"parts": [{
		"partsId": 6,
		"orderId": "pay201905240956173UF9N5K9TO2ST",
		"sort": 1,
		"partsName": "备胎55",
		"num": 1,
		"qualityType": 3,
		"amount": 222,
		"remarks": "十层新",
		"del": 0,
		"creater": 7,
		"updater": 7,
		"created": "2019-05-24T03:55:00.000+0000",
		"updated": "2019-05-24T03:55:00.000+0000"
	}],
	"picUrls": []
}*/
class MBillDetailScreen extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      modalContent: "可以从推荐您使用本app的用户那里获得", //弹框内容
      orderId: null,
      amount: 0, //金额
      payTime: "",
      payMode: 0, //订单状态1 直接支付 2 货到付款
      payState: null, //1已经支付2，已关闭（3.关闭 拒收）
      receiveGoodsState: null, //0未收货 1 已收货 2，拒收
      payRemarks: null,
      refundAmount: 0, //退款金额
      companyName: "",
      companyPhone: "",
      name: null,
      deliveryPhone: null,
      deliveryId: null,
      parts: [], //配件清单
      picUrls: [], //图片列表
      selected: 0, //0拒收 1 确定收货
      totalnum: 0, //总计

      // 剩余确认收货时间 String
      leftTimeForReceive: "5天10小时"
    };
  }

  componentWillUnmount() {}

  componentDidMount() {
    this.getData();
  }

  getData = () => {
    let { orderId } = this.props.navigation.state.params;
    let params = { orderId: orderId };
    requestApi
      .orderDetails(params)
      .then(data => {
        let totalnum = 0;
        if (Array.isArray(data.parts)) {
          totalnum = data.parts.reduce((sum, curr) => sum + curr.amount*curr.num, 0);
        }
        this.setState({
          orderId: data.orderId,
          amount: data.amount, //金额
          payTime: data.payTime,
          payMode: data.payMode,
          payState: data.payState, //订单状态0已支付，1已关闭，2代收获
          payRemarks: data.payRemarks,
          refundAmount: data.refundAmount, //退款金额
          companyName: data.companyName,
          companyPhone: data.companyPhone,
          name: data.name,
          deliveryPhone: data.deliveryPhone,
          parts: data.parts, //配件清单
          picUrls: data.picUrls, //图片列表
          receiveGoodsState: data.receiveGoodsState,
          totalnum: totalnum,
          leftTimeForReceive: data.payTimeStr
        });
      })
      .catch(err => {
        //alert(JSON.stringify(err, null, 2));
        Toast.show(err.msg, 1000);
      });
  };

  render() {
    const { data, hasMore } = this.state;
    return (
      <View style={{ flex: 1, backgroundColor: "#F9F9F9" }}>
        <NavigationBar
          navigation={this.props.navigation}
          isBack={true}
          title={"详情"}
        />
        <ScrollView style={{ flex: 1 }} alwaysBounceVertical={true}>
          <View style={styles.divideStyle} />
          {this._orderdetail()}
          <View style={styles.divideStyle} />
          {this._renderpartslist()}
          <View style={styles.divideStyle} />
          {this._renderRemark()}
          <View style={styles.divideStyle} />
          {this.state.receiveGoodsState != null &&
          this.state.receiveGoodsState == 0 ? (
            <View>
              <TouchableOpacity
                style={{
                  backgroundColor: "#fff",
                  flexDirection: "row",
                  height: 60,
                  paddingLeft: 15,
                  paddingRight: 15,
                  alignItems: "center",
                  justifyContent: "center"
                }}
                onPress={() => {
                  //选择配送人
                  NavigationService.navigate("DeliverySearchScreen", {
                    callback: res => {
                      //回调函数
                      this.setState({
                        name: res.name,
                        deliveryPhone: res.deliveryPhone,
                        deliveryId: res.deliveryId
                      });
                    }
                  });
                }}
              >
                <Text style={{ color: "#606060", fontSize: 16 }}>配送人</Text>
                <View style={{ flex: 1 }} />
                <Text style={{ color: "#AAAAAA", fontSize: 14 }}>
                  {this.state.name ? this.state.name : "请选择"}{" "}
                  {this.state.deliveryPhone}
                </Text>
              </TouchableOpacity>
              <View style={styles.divideStyle} />
            </View>
          ) : null}
          {this.state.receiveGoodsState != null ? this._orderState() : null}
        </ScrollView>

        <Confirm
          ref="modal"
          cancelClick={this.cancelDetailModal.bind(this)}
          sureClick={this.sureDetailModal.bind(this)}
          content={this.state.modalContent}
        />
        <View style={{ height: safeAreaBottomHeight }} />
      </View>
    );
  }

  //订单详情
  _orderdetail = () => {
    return (
      <View
        style={{
          backgroundColor: "#fff",
          flexDirection: "row",
          flex: 1,
          paddingTop: 20,
          paddingBottom: 10,
          alignItems: "center"
        }}
      >
        <View style={{ flex: 1 }}>
          <View
            style={{
              width: "100%",
              backgroundColor: "#fff",
              flexDirection: "row",
              alignItems: "flex-end"
            }}
          >
            <Text
              style={{ marginLeft: 15, color: "#4A4A4A", fontSize: 25 }}
              numberOfLines={1}
            >
              ¥ {this.state.amount}
            </Text>
            {this.state.refundAmount > 0 ? (
              <Text
                style={{
                  paddingBottom: 5,
                  marginLeft: 15,
                  color: "#D0021B",
                  fontSize: 13
                }}
                numberOfLines={1}
              >
                退款：¥{this.state.refundAmount}
              </Text>
            ) : null}
          </View>

          <Text
            style={{
              marginTop: 20,
              marginLeft: 15,
              color: "#606060",
              fontSize: 14
            }}
            numberOfLines={1}
          >
            收款方：{this.state.companyName}
          </Text>

          <View
            style={{
              marginTop: 10,
              width: "100%",
              backgroundColor: "#fff",
              flexDirection: "row",
              alignItems: "flex-end"
            }}
          >
            <Text
              style={{ marginLeft: 15, color: "#AAAAAA", fontSize: 10 }}
              numberOfLines={1}
            >
              支付单号：{this.state.orderId}
            </Text>
            <TouchableOpacity
              style={{ marginLeft: 15 }}
              onPress={() => {
                //复制
                if (this.state.orderId != null) {
                  Clipboard.setString(this.state.orderId);
                  Toast.show("复制成功");
                }
              }}
            >
              <Text style={{ color: "#4A90E2", fontSize: 12 }}>复制</Text>
            </TouchableOpacity>
          </View>
          <Text
            style={{
              marginTop: 10,
              marginLeft: 15,
              color: "#AAAAAA",
              fontSize: 10
            }}
            numberOfLines={1}
          >
            支付时间：{this.state.payTime}
          </Text>
        </View>

        <TouchableOpacity
          style={{
            marginRight: 15,
            width: 60,
            height: 20,
            justifyContent: "center",
            alignItems: "center",
            borderRadius: 5,
            borderWidth: 1,
            borderColor: "#4A90E2"
          }}
          onPress={() => {
              let tel = `tel:${this.state.companyPhone}`// 目标电话
              Linking.canOpenURL(tel).then((supported) => {
                  if (!supported) {
                      Toast.show("唤起失败",500)
                  } else {
                      return Linking.openURL(tel)
                  }
              }).catch(error =>{
                  Toast.show("唤起失败",500)
              })
          }}
        >
          <Text style={{ color: "#4A90E2", fontSize: 12 }}>联系商家</Text>
        </TouchableOpacity>
      </View>
    );
  };
  //配件清单
  _renderpartslist = () => {
    return (
      <View
        style={{
          backgroundColor: "#fff",
          flex: 1,
          paddingTop: 15,
          paddingBottom: 15
        }}
      >
        <Text
          style={{
            marginLeft: 15,
            color: "#606060",
            fontSize: 16,
            marginBottom: 10
          }}
        >
          配件清单({this.state.parts.length})
        </Text>

        <FlatList
          style={{
            backgroundColor: "#fff",
            // borderColor: "#DDDDDD",borderWidth: 0.5,
            marginRight: 15,
            marginLeft: 15
          }}
          scrollEnabled={false}
          data={this.state.parts}
          horizontal={false}
          keyExtractor={(item, index) => index.toString()}
          renderItem={this._renderItem}
          ListEmptyComponent={() => <FlatListEmpty />}
        />
        <View
          style={{
            flexDirection: "row",
            backgroundColor: "#fff"
          }}
        >
          <View style={{ flex: 1 }} />
          <Text
            style={{
              marginRight: 15,
              color: "#606060",
              fontSize: 16,
              marginTop: 10
            }}
          >
            总计{this.state.totalnum}元
          </Text>
        </View>
      </View>
    );
  };

  _renderItem = ({ item }) => (
    <MyListItem onPressItem={this._onPressItem.bind(this)} item={item} />
  );

  _onPressItem = (index, partsId) => {
    //取出数据重新排序index： 0向上 1向下
    let newdata = [...this.state.parts];
    const prevIndex = this.state.parts.findIndex(
      item => item.partsId === partsId
    );
    if (
      (prevIndex == 0 && index == 0) ||
      (index == 1 && prevIndex + 1 == this.state.parts.length)
    ) {
      //最上面不能向上移动  最下面不能向下移动
      return;
    }
    let newitem = newdata[prevIndex];
    newdata.splice(prevIndex, 1); //移除这个数据

    if (index == 0 && prevIndex - 1 >= 0) {
      newdata.splice(prevIndex - 1, 0, newitem); //插入向上
      this.setState({ parts: newdata });
    } else if (index == 1 && prevIndex + 1 <= this.state.parts.length) {
      newdata.splice(prevIndex + 1, 0, newitem); //插入向下
      this.setState({ parts: newdata });
    }
  };

  //订单备注
  _renderRemark = () => {
    return (
      <View
        style={{
          backgroundColor: "#fff",
          flex: 1,
          paddingTop: 15,
          paddingLeft: 15,
          paddingRight: 15,
          paddingBottom: 15
        }}
      >
        <Text
          style={{
            color: "#606060",
            fontSize: 16
          }}
        >
          支付单备注
        </Text>

        <Text
          style={{
            marginTop: 15,
            color: "#AAAAAA",
            fontSize: 14
          }}
        >
          {this.state.payRemarks}
        </Text>

        <ScrollView
          style={{
            width: "100%",
            marginTop: 10,
            backgroundColor: "#fff",
            height: 50
          }}
          horizontal={true}
        >
          <FlatList
            style={{ backgroundColor: "#fff" }}
            scrollEnabled={false}
            data={this.state.picUrls}
            horizontal={true}
            keyExtractor={(item, index) => index.toString()}
            renderItem={({ item, index }) => {
              return (
                <ImageView
                  source={{ uri: "http://cdn.traceche.com/" + item }}
                  style={{
                    borderRadius: 2,
                    marginRight: 10,
                    width: 45,
                    height: 45
                  }}
                />
              );
            }}
          />
        </ScrollView>
      </View>
    );
  };

  //receiveGoodsState 0 未收货 1已经收货
  _orderState = () => {
    const { leftTimeForReceive } = this.state;
    return this.state.receiveGoodsState == 0 ? (
      <View
        style={{
          backgroundColor: "#fff",
          alignItems: "center",
          justifyContent: "center"
        }}
      >
        <View
          style={{
            backgroundColor: "#fff",
            height: 70,
            width: "100%",
            flexDirection: "row",
            alignItems: "center",
            justifyContent: "center"
          }}
        >
          <TouchableOpacity
            style={{
              flex: 1,
              marginLeft: 15,
              marginRight: 15,
              height: 45,
              borderRadius: 6,
              backgroundColor: "#D0021B",
              justifyContent: "center",
              alignItems: "center"
            }}
            onPress={() => {
              this.setState({
                selected: 0,
                modalContent: "拒收后将直接关闭支付单，确认操作？"
              });
              this.refs.modal.show();
            }}
          >
            <Text style={{ color: "#fff", fontSize: 14 }}>拒收</Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={{
              flex: 1,
              marginLeft: 15,
              marginRight: 15,
              height: 45,
              borderRadius: 6,
              backgroundColor: "#4A90E2",
              justifyContent: "center",
              alignItems: "center"
            }}
            onPress={() => {
              if (this.state.deliveryId) {
                this.setState({
                  selected: 1,
                  modalContent: "确认收货后款项将直接转入卖家账户，确认操作？"
                });
                this.refs.modal.show();
              } else {
                Toast.show("请选择配送人", 1000);
              }
            }}
          >
            <Text style={{ color: "#fff", fontSize: 14 }}>确认收货</Text>
          </TouchableOpacity>
        </View>
        <Text
          style={{
            marginTop: 10,
            marginBottom: 20,
            color: "#ccc",
            fontSize: 16
          }}
        >{`离确认收货还剩${leftTimeForReceive}`}</Text>
      </View>
    ) : (
      <View
        style={{
          backgroundColor: "#fff",
          height: 70,
          width: "100%",
          flexDirection: "row",
          alignItems: "center",
          justifyContent: "center"
        }}
      >
        <View
          style={{
            flex: 1,
            marginLeft: 15,
            marginRight: 15,
            height: 45,
            borderRadius: 6,
            backgroundColor: "#CCCCCC",
            justifyContent: "center",
            alignItems: "center"
          }}
        >
          <Text style={{ color: "#fff", fontSize: 14 }}>
            {this.state.payState === 1 ? "已支付" : "已关闭"}
          </Text>
        </View>
      </View>
    );
  };

  cancelDetailModal() {}

  //拒收和确定收货
  sureDetailModal() {
    let { orderId, deliveryId, selected } = this.state;
    if (selected == 0) {
      requestApi
        .refuseOrder({ deliveryId: deliveryId, orderId: orderId })
        .then(data => {
          Toast.show("操作成功", 1000);
          //DeviceEventEmitter.emit(SureGoods, "发送拒绝收货通知");
          this.getData();
          const reloadList = _.get(
            this,
            "props.navigation.state.params.reloadList"
          );
          if (_.isFunction(reloadList)) {
            reloadList();
          }
        })
        .catch(err => {
          Toast.show(err.msg, 1000);
        });
    } else {
      requestApi
        .confirmReceipt({ deliveryId: deliveryId, orderId: orderId })
        .then(data => {
          Toast.show("操作成功", 1000);
          //DeviceEventEmitter.emit(SureGoods, "发送确认收货通知");
          this.getData();
          const reloadList = _.get(
            this,
            "props.navigation.state.params.reloadList"
          );
          if (_.isFunction(reloadList)) {
            reloadList();
          }
        })
        .catch(err => {
          Toast.show(err.msg, 1000);
        });
    }
  }
}

const styles = StyleSheet.create({
  divideStyle: {
    height: 10,
    backgroundColor: "#F9F9F9"
  }
});

class MyListItem extends PureComponent {
  _onPress = index => {
    this.props.onPressItem(index, this.props.item.partsId);
  };

  render() {
    return (
      <View
        style={{
          minheight: 90,
          flex: 1,
          borderColor: "#DDDDDD",
          borderWidth: 0.5
        }}
      >
        <View style={{ minheight: 45, flexDirection: "row" }}>
          <TouchableOpacity
            style={{
              minheight: 45,
              width: 45,
              borderColor: "#DDDDDD",
              borderWidth: 0.5,
              justifyContent: "center",
              alignItems: "center"
            }}
            onPress={() => {
              this._onPress(0);
            }}
          >
            <Image
              source={image.ic_up_arrow}
              style={{ width: 20, height: 20 }}
            />
          </TouchableOpacity>

          <View
            style={{
              flex: 1,
              backgroundColor: "#fff",
              flexDirection: "row",
              borderColor: "#DDDDDD",
              borderWidth: 0.5,
              paddingRight: 15,
              paddingLeft: 15,
              alignItems: "center",
              justifyContent: "center"
            }}
          >
            <Text style={{ color: "#606060", fontSize: 16 }}>
              {this.props.item.partsName} X {this.props.item.num}
            </Text>
            <View style={{ flex: 1 }} />
            <Text style={{ color: "#606060", fontSize: 14 }}>
              ¥{this.props.item.amount}
            </Text>
          </View>
        </View>
        <View style={{ minheight: 45, flexDirection: "row" }}>
          <TouchableOpacity
            style={{
              minheight: 45,
              width: 45,
              borderColor: "#DDDDDD",
              borderWidth: 0.5,
              justifyContent: "center",
              alignItems: "center"
            }}
            onPress={() => {
              this._onPress(1);
            }}
          >
            <Image
              source={image.ic_down_arrow}
              style={{ width: 20, height: 20 }}
            />
          </TouchableOpacity>

          <View
            style={{
              flex: 1,
              backgroundColor: "#fff",
              flexDirection: "row",
              borderColor: "#DDDDDD",
              borderWidth: 0.5,
              paddingRight: 15,
              paddingLeft: 15,
              alignItems: "center",
              justifyContent: "center"
            }}
          >
            <Text style={{ color: "#606060", fontSize: 16 }}>
              {this.props.item.remarks}
            </Text>
            <View style={{ flex: 1 }} />
          </View>
        </View>
      </View>
    );
  }
}

export default connect(
  ({ userInfo }) => ({
    userInfo
  }),
  {
    getSearchListData: actions.getSearchListData
  }
)(MBillDetailScreen);
